import { defineStore } from 'pinia'
import { useItemsStore } from './items'

export const useStatisticsStore = defineStore('statistics', {
    state: () => ({
        loading: false,
        error: null,

        // 模拟数据 - 花销分布
        spendingDistribution: {
            loaded: true,
            data: [
                { name: '电子产品', value: 16707, percentage: 32.5, color: '#0071e3' },
                { name: '办公文具', value: 6449.77, percentage: 12.5, color: '#34c759' },
                { name: '家具', value: 5230, percentage: 10.2, color: '#ff9500' },
                { name: '厨房用品', value: 4150, percentage: 8.1, color: '#5e5ce6' },
                { name: '服装', value: 3860, percentage: 7.5, color: '#ff3b30' },
                { name: '其他', value: 15080, percentage: 29.2, color: '#a2a2a7' },
            ]
        },

        // 模拟数据 - 购买渠道分布
        channelDistribution: {
            loaded: true,
            data: [
                { name: '京东', value: 6000, percentage: 22.6, color: '#e1251b' },
                { name: '淘宝', value: 7000, percentage: 26.4, color: '#ff5000' },
                { name: '线下商店', value: 5200, percentage: 19.6, color: '#34c759' },
                { name: '拼多多', value: 3800, percentage: 14.3, color: '#e02e24' },
                { name: '天猫', value: 4500, percentage: 17.1, color: '#ff0036' }
            ]
        },

        // 模拟数据 - 物品花销排行
        spendingRank: {
            loaded: true,
            data: [
                { name: '学习计算器', value: 5300, trend: 0 },
                { name: 'iPhone 11', value: 5297, trend: -2 },
                { name: 'iPad', value: 2849, trend: 0 },
                { name: 'iPhone 7 Plus', value: 2597, trend: -5 },
                { name: '机械键盘', value: 1450, trend: 0 },
                { name: '显示器', value: 1399, trend: 0 },
                { name: '耳机', value: 1299, trend: 0 },
                { name: '电饭煲', value: 899, trend: 0 }
            ]
        },

        // 模拟数据 - 持有天数排行
        holdingDaysRank: {
            loaded: true,
            data: [
                { name: '考试计算器', days: 3735, trend: 0 },
                { name: '黑白配鼠标', days: 2547, trend: 0 },
                { name: '灰色电动牙刷', days: 2547, trend: 0 },
                { name: 'U盘', days: 2547, trend: 0 },
                { name: '保温杯', days: 1825, trend: 0 },
                { name: '台灯', days: 1460, trend: 0 },
                { name: '剃须刀', days: 1095, trend: 0 },
                { name: '雨伞', days: 730, trend: 0 }
            ]
        },

        // 模拟数据 - 物品类别分布
        categoryDistribution: {
            loaded: true,
            data: [
                { name: '电子产品', count: 32, percentage: 31.4, color: '#007aff' },
                { name: '家具', count: 24, percentage: 23.5, color: '#ff9500' },
                { name: '厨房用品', count: 18, percentage: 17.6, color: '#34c759' },
                { name: '办公文具', count: 14, percentage: 13.7, color: '#5e5ce6' },
                { name: '生活用品', count: 9, percentage: 8.8, color: '#ff3b30' },
                { name: '其他', count: 5, percentage: 5.0, color: '#a2a2a7' }
            ]
        },

        // 模拟数据 - 储存位置分布
        locationDistribution: {
            loaded: true,
            data: [
                { name: '客厅', count: 35, percentage: 28.0, color: '#007aff' },
                { name: '卧室', count: 28, percentage: 22.4, color: '#5e5ce6' },
                { name: '书房', count: 22, percentage: 17.6, color: '#ff9500' },
                { name: '厨房', count: 20, percentage: 16.0, color: '#34c759' },
                { name: '阳台', count: 12, percentage: 9.6, color: '#ff3b30' },
                { name: '其他', count: 8, percentage: 6.4, color: '#a2a2a7' }
            ]
        },

        // 模拟数据 - 物品状态分布
        statusDistribution: {
            loaded: true,
            data: [
                { name: '正常使用', count: 98, percentage: 78.4, color: '#34c759' },
                { name: '需要替换', count: 15, percentage: 12.0, color: '#ff9500' },
                { name: '需要维修', count: 8, percentage: 6.4, color: '#ff3b30' },
                { name: '已停用', count: 4, percentage: 3.2, color: '#a2a2a7' }
            ]
        },

        // 模拟数据 - 月度支出趋势
        monthlySpendingTrend: {
            loaded: true,
            data: [
                { month: '1月', value: 4500 },
                { month: '2月', value: 3200 },
                { month: '3月', value: 5800 },
                { month: '4月', value: 2900 },
                { month: '5月', value: 4100 },
                { month: '6月', value: 6200 },
                { month: '7月', value: 3700 },
                { month: '8月', value: 4900 },
                { month: '9月', value: 5300 },
                { month: '10月', value: 4700 },
                { month: '11月', value: 7200 },
                { month: '12月', value: 8500 }
            ]
        },

        // 模拟数据 - 使用频率分布
        usageFrequencyDistribution: {
            loaded: true,
            data: [
                { frequency: '每日使用', count: 42, percentage: 33.6, color: '#007aff' },
                { frequency: '每周使用', count: 35, percentage: 28.0, color: '#34c759' },
                { frequency: '每月使用', count: 28, percentage: 22.4, color: '#ff9500' },
                { frequency: '偶尔使用', count: 15, percentage: 12.0, color: '#ff3b30' },
                { frequency: '从未使用', count: 5, percentage: 4.0, color: '#a2a2a7' }
            ]
        },

        // 模拟数据 - 物品评分分析
        itemRatingAnalysis: {
            loaded: true,
            data: [
                { rating: 5, count: 65, percentage: 52.0 },
                { rating: 4, count: 35, percentage: 28.0 },
                { rating: 3, count: 15, percentage: 12.0 },
                { rating: 2, count: 8, percentage: 6.4 },
                { rating: 1, count: 2, percentage: 1.6 }
            ],
            averageRating: 4.2
        }
    }),

    getters: {
        // 按位置统计物品数量
        getItemCountByLocation: () => {
            const itemsStore = useItemsStore()
            const locationStats = {}

            itemsStore.locations.forEach(location => {
                locationStats[location.name] = itemsStore.items.filter(item => item.locationId === location.id).length
            })

            return locationStats
        },

        // 按分类统计物品数量
        getItemCountByCategory: () => {
            const itemsStore = useItemsStore()
            const categoryStats = {}

            itemsStore.categories.forEach(category => {
                categoryStats[category.name] = itemsStore.items.filter(item => item.categoryId === category.id).length
            })

            return categoryStats
        },

        // 物品价值统计（如果物品有价格属性）
        getTotalItemsValue: () => {
            const itemsStore = useItemsStore()
            return itemsStore.items.reduce((total, item) => {
                return total + (parseFloat(item.price || 0) * (item.quantity || 1))
            }, 0)
        },

        // 库存价值按分类统计
        getValueByCategory: () => {
            const itemsStore = useItemsStore()
            const categoryValue = {}

            itemsStore.categories.forEach(category => {
                const items = itemsStore.items.filter(item => item.categoryId === category.id)
                categoryValue[category.name] = items.reduce((total, item) => {
                    return total + (parseFloat(item.price || 0) * (item.quantity || 1))
                }, 0)
            })

            return categoryValue
        },

        // 获取最近购买的物品
        getRecentPurchases: () => {
            const itemsStore = useItemsStore()
            return [...itemsStore.items]
                .filter(item => item.purchaseDate)
                .sort((a, b) => new Date(b.purchaseDate) - new Date(a.purchaseDate))
                .slice(0, 5) // 获取最近5个
        },

        // 获取统计图表所需数据
        getChartData: (state) => {
            return {
                locationData: {
                    labels: Object.keys(state.getItemCountByLocation),
                    values: Object.values(state.getItemCountByLocation)
                },
                categoryData: {
                    labels: Object.keys(state.getItemCountByCategory),
                    values: Object.values(state.getItemCountByCategory)
                },
                valueData: {
                    labels: Object.keys(state.getValueByCategory),
                    values: Object.values(state.getValueByCategory)
                }
            }
        },

        // 获取物品花销分布数据
        getSpendingDistribution: (state) => state.spendingDistribution,

        // 获取购买渠道分布数据
        getChannelDistribution: (state) => state.channelDistribution,

        // 获取物品花销排行数据
        getSpendingRank: (state) => state.spendingRank,

        // 获取持有天数排行数据
        getHoldingDaysRank: (state) => state.holdingDaysRank,

        // 获取物品类别分布数据
        getCategoryDistribution: (state) => state.categoryDistribution,

        // 获取储存位置分布数据
        getLocationDistribution: (state) => state.locationDistribution,

        // 获取物品状态分布数据
        getStatusDistribution: (state) => state.statusDistribution,

        // 获取月度支出趋势数据
        getMonthlySpendingTrend: (state) => state.monthlySpendingTrend,

        // 获取使用频率分布数据
        getUsageFrequencyDistribution: (state) => state.usageFrequencyDistribution,

        // 获取物品评分分析数据
        getItemRatingAnalysis: (state) => state.itemRatingAnalysis,

        // 新增: 计算本月新增物品数量
        getNewItemsThisMonth: () => {
            const itemsStore = useItemsStore()
            const now = new Date()
            const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)

            return itemsStore.items.filter(item => {
                const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null
                return purchaseDate && purchaseDate >= firstDayOfMonth
            }).length
        },

        // 新增: 计算物品持有时间统计
        getItemHoldingDaysStats: () => {
            const itemsStore = useItemsStore()
            const today = new Date()

            // 计算每个物品的持有天数
            const itemsWithDays = itemsStore.items
                .filter(item => item.purchaseDate)
                .map(item => {
                    const purchaseDate = new Date(item.purchaseDate)
                    const diffTime = Math.abs(today - purchaseDate)
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
                    return {
                        ...item,
                        holdingDays: diffDays
                    }
                })

            // 计算平均持有天数
            const totalDays = itemsWithDays.reduce((sum, item) => sum + item.holdingDays, 0)
            const averageDays = itemsWithDays.length > 0 ? Math.round(totalDays / itemsWithDays.length) : 0

            // 持有时间分布
            const holdingDistribution = [
                { range: '1个月内', count: 0, days: 30 },
                { range: '1-3个月', count: 0, days: 90 },
                { range: '3-6个月', count: 0, days: 180 },
                { range: '6-12个月', count: 0, days: 365 },
                { range: '1-2年', count: 0, days: 730 },
                { range: '2年以上', count: 0, days: Infinity }
            ]

            itemsWithDays.forEach(item => {
                for (const range of holdingDistribution) {
                    if (item.holdingDays <= range.days) {
                        range.count++
                        break
                    }
                }
            })

            return {
                averageDays,
                longestHeldItem: [...itemsWithDays].sort((a, b) => b.holdingDays - a.holdingDays)[0] || null,
                newestItem: [...itemsWithDays].sort((a, b) => a.holdingDays - b.holdingDays)[0] || null,
                distribution: holdingDistribution
            }
        },

        // 新增: 计算价格区间统计
        getPriceRangeStats: () => {
            const itemsStore = useItemsStore()

            // 价格区间定义
            const priceRanges = [
                { range: '100元以下', count: 0, value: 0, upperLimit: 100 },
                { range: '100-500元', count: 0, value: 0, upperLimit: 500 },
                { range: '500-1000元', count: 0, value: 0, upperLimit: 1000 },
                { range: '1000-5000元', count: 0, value: 0, upperLimit: 5000 },
                { range: '5000元以上', count: 0, value: 0, upperLimit: Infinity }
            ]

            // 统计各价格区间的物品
            itemsStore.items.forEach(item => {
                const price = parseFloat(item.price || 0)
                for (const range of priceRanges) {
                    if (price <= range.upperLimit) {
                        range.count += (item.quantity || 1)
                        range.value += price * (item.quantity || 1)
                        break
                    }
                }
            })

            // 计算平均物品价格
            const totalValue = itemsStore.items.reduce((sum, item) => sum + parseFloat(item.price || 0), 0)
            const averagePrice = itemsStore.items.length > 0 ? totalValue / itemsStore.items.length : 0

            return {
                averagePrice,
                ranges: priceRanges,
                mostExpensiveItem: [...itemsStore.items].sort((a, b) => parseFloat(b.price || 0) - parseFloat(a.price || 0))[0] || null
            }
        },

        // 新增: 计算使用状态分析
        getStatusAnalysis: () => {
            const itemsStore = useItemsStore()
            const statusCounts = {}

            // 计算每种状态的物品数量
            itemsStore.statuses.forEach(status => {
                statusCounts[status.name] = itemsStore.items.filter(item => item.status === status.value).length
            })

            // 计算需要关注的物品
            const needAttention = itemsStore.items.filter(item => {
                const status = item.status
                return status === 'need_repair' || status === 'need_replace' || status === 'expired'
            })

            return {
                statusCounts,
                needAttention
            }
        }
    },

    actions: {
        // 新增: 分析物品列表并生成统计数据
        analyzeItems() {
            this.loading = true
            try {
                const itemsStore = useItemsStore()
                const allItems = itemsStore.items || []

                if (allItems.length === 0) {
                    throw new Error('没有物品数据可分析')
                }

                // 更新花销分布数据
                this.updateSpendingDistribution(allItems)

                // 更新类别分布数据
                this.updateCategoryDistribution(allItems)

                // 更新位置分布数据
                this.updateLocationDistribution(allItems)

                // 更新状态分布数据
                this.updateStatusDistribution(allItems)

                // 更新月度支出趋势
                this.updateMonthlySpendingTrend(allItems)

                // 更新物品价格排行榜
                this.updateSpendingRank(allItems)

                // 更新物品持有天数排行榜
                this.updateHoldingDaysRank(allItems)

                return true
            } catch (error) {
                console.error('分析物品数据失败', error)
                return false
            } finally {
                this.loading = false
            }
        },

        // 更新花销分布数据
        updateSpendingDistribution(items) {
            const itemsStore = useItemsStore()
            const categorySpending = {}
            let totalSpending = 0

            // 按分类汇总花销
            items.forEach(item => {
                const categoryName = itemsStore.getCategoryName(item.categoryId) || '其他'
                const itemValue = parseFloat(item.price || 0) * (item.quantity || 1)
                totalSpending += itemValue

                if (!categorySpending[categoryName]) {
                    categorySpending[categoryName] = 0
                }
                categorySpending[categoryName] += itemValue
            })

            // 转换为数组格式并计算百分比
            const categoryColors = {
                '电子产品': '#0071e3',
                '家具': '#ff9500',
                '厨房用品': '#34c759',
                '衣物': '#5e5ce6',
                '日用品': '#ff3b30',
                '其他': '#a2a2a7'
            }

            const spendingData = Object.keys(categorySpending).map((name, index) => {
                return {
                    name,
                    value: categorySpending[name],
                    percentage: totalSpending > 0 ? (categorySpending[name] / totalSpending * 100).toFixed(1) : 0,
                    color: categoryColors[name] || Object.values(categoryColors)[index % Object.values(categoryColors).length]
                }
            }).sort((a, b) => b.value - a.value)

            // 更新状态
            this.spendingDistribution = {
                loaded: true,
                data: spendingData
            }
        },

        // 更新类别分布数据
        updateCategoryDistribution(items) {
            const itemsStore = useItemsStore()
            const categoryCounts = {}

            // 按分类统计物品数量
            items.forEach(item => {
                const categoryName = itemsStore.getCategoryName(item.categoryId) || '未分类'
                if (!categoryCounts[categoryName]) {
                    categoryCounts[categoryName] = 0
                }
                categoryCounts[categoryName] += (item.quantity || 1)
            })

            // 转换为数组格式并计算百分比
            const totalItems = items.reduce((sum, item) => sum + (item.quantity || 1), 0)
            const categoryColors = {
                '电子产品': '#007aff',
                '家具': '#ff9500',
                '厨房用品': '#34c759',
                '办公文具': '#5e5ce6',
                '生活用品': '#ff3b30',
                '其他': '#a2a2a7'
            }

            const categoryData = Object.keys(categoryCounts).map((name, index) => {
                return {
                    name,
                    count: categoryCounts[name],
                    percentage: totalItems > 0 ? (categoryCounts[name] / totalItems * 100).toFixed(1) : 0,
                    color: categoryColors[name] || Object.values(categoryColors)[index % Object.values(categoryColors).length]
                }
            }).sort((a, b) => b.count - a.count)

            // 更新状态
            this.categoryDistribution = {
                loaded: true,
                data: categoryData
            }
        },

        // 更新位置分布数据
        updateLocationDistribution(items) {
            const itemsStore = useItemsStore()
            const locationCounts = {}

            // 按位置统计物品数量
            items.forEach(item => {
                // 优先使用 specificLocation，如果不存在则尝试从 locationId 获取位置名称
                const locationName = item.specificLocation ||
                    itemsStore.getLocationName(item.locationId) ||
                    '未知位置'

                if (!locationCounts[locationName]) {
                    locationCounts[locationName] = 0
                }
                locationCounts[locationName] += (item.quantity || 1)
            })

            // 转换为数组格式并计算百分比
            const totalItems = items.reduce((sum, item) => sum + (item.quantity || 1), 0)
            const locationColors = {
                '客厅': '#007aff',
                '卧室': '#5e5ce6',
                '书房': '#ff9500',
                '厨房': '#34c759',
                '阳台': '#ff3b30',
                '其他': '#a2a2a7'
            }

            const locationData = Object.keys(locationCounts).map((name, index) => {
                return {
                    name,
                    count: locationCounts[name],
                    percentage: totalItems > 0 ? (locationCounts[name] / totalItems * 100).toFixed(1) : 0,
                    color: locationColors[name] || Object.values(locationColors)[index % Object.values(locationColors).length]
                }
            }).sort((a, b) => b.count - a.count)

            // 更新状态
            this.locationDistribution = {
                loaded: true,
                data: locationData
            }
        },

        // 更新状态分布数据
        updateStatusDistribution(items) {
            const itemsStore = useItemsStore()
            const statusCounts = {}

            // 按状态统计物品数量
            items.forEach(item => {
                const statusName = itemsStore.getStatusName(item.status) || '未知状态'
                if (!statusCounts[statusName]) {
                    statusCounts[statusName] = 0
                }
                statusCounts[statusName] += (item.quantity || 1)
            })

            // 转换为数组格式并计算百分比
            const totalItems = items.reduce((sum, item) => sum + (item.quantity || 1), 0)
            const statusColors = {
                '正常使用': '#34c759',
                '需要替换': '#ff9500',
                '需要维修': '#ff3b30',
                '已停用': '#a2a2a7',
                '已过期': '#ff3b30',
                '已损坏': '#ff3b30',
                '闲置': '#a2a2a7'
            }

            const statusData = Object.keys(statusCounts).map((name) => {
                return {
                    name,
                    count: statusCounts[name],
                    percentage: totalItems > 0 ? (statusCounts[name] / totalItems * 100).toFixed(1) : 0,
                    color: statusColors[name] || '#8e8e93'
                }
            }).sort((a, b) => b.count - a.count)

            // 更新状态
            this.statusDistribution = {
                loaded: true,
                data: statusData
            }
        },

        // 更新月度支出趋势
        updateMonthlySpendingTrend(items) {
            // 创建月度映射
            const monthlyDataMap = {}
            const now = new Date()

            // 初始化12个月
            for (let i = 1; i <= 12; i++) {
                const monthKey = `${i}月`
                monthlyDataMap[monthKey] = { month: monthKey, value: 0, count: 0 }
            }

            // 统计月度数据
            items.forEach(item => {
                if (item.purchaseDate) {
                    const purchaseDate = new Date(item.purchaseDate)
                    if (purchaseDate.getFullYear() === now.getFullYear()) {
                        const monthKey = `${purchaseDate.getMonth() + 1}月`
                        if (monthlyDataMap[monthKey]) {
                            monthlyDataMap[monthKey].value += (parseFloat(item.price || 0) * (item.quantity || 1))
                            monthlyDataMap[monthKey].count += 1
                        }
                    }
                }
            })

            // 转换为数组
            const monthlySpendingData = Object.values(monthlyDataMap)

            // 更新状态
            this.monthlySpendingTrend = {
                loaded: true,
                data: monthlySpendingData
            }
        },

        // 更新物品价格排行榜
        updateSpendingRank(items) {
            // 复制物品数组并根据价格排序
            const spendingRankData = [...items]
                .filter(item => item.price && !isNaN(parseFloat(item.price)))
                .sort((a, b) => (parseFloat(b.price || 0) - parseFloat(a.price || 0)))
                .slice(0, 10) // 增加数量到10个，与视图保持一致
                .map(item => ({
                    name: item.name || '未命名物品',
                    value: parseFloat(item.price || 0),
                    purchaseDate: item.purchaseDate || null, // 添加purchaseDate字段
                    trend: 0 // 这里可以与历史数据比较
                }))

            // 更新状态
            this.spendingRank = {
                loaded: true,
                data: spendingRankData
            }
        },

        // 更新物品持有天数排行榜
        updateHoldingDaysRank(items) {
            const today = new Date()

            // 计算持有天数并排序
            const holdingDaysRankData = [...items]
                .filter(item => item.purchaseDate)
                .map(item => {
                    const purchaseDate = new Date(item.purchaseDate)
                    const diffTime = Math.abs(today - purchaseDate)
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
                    return {
                        name: item.name,
                        days: diffDays,
                        trend: 0
                    }
                })
                .sort((a, b) => b.days - a.days)
                .slice(0, 8)

            // 更新状态
            this.holdingDaysRank = {
                loaded: true,
                data: holdingDaysRankData
            }
        }
    }
}) 